#include <stdlib.h>
#include "smallsatos.h"
#include "log.h"
#include "storage.h"
#include "int_eeprom.h"
#include "rtc.h"

extern time_t system_time; /* see rtc.c */

void* event_log_queue_content[EVENT_LOG_QUEUE_SIZE];
OS_EVENT* event_log_queue;

OS_EVENT* get_event_log_queue()
{
	return event_log_queue;
}

void event_log(void* pdata)
{
	INT16U err;
	INT8U courant;

	evenement_t* data_ptr;
	time_t now;
	priorite_evenement_t prio;

	INT8U entry_size = sizeof(time_t) + sizeof(unsigned char) + sizeof(unsigned int);
	INT8U i;

	eeprom_query query;
	eeprom_query* rep;
	INT16U nb_occ;
	INT16U addr_base;

	event_log_queue = OSQCreate(&event_log_queue_content, EVENT_LOG_QUEUE_SIZE);

	courant = 0;

	for(;;)
	{

		data_ptr = (evenement_t*)OSQPend(event_log_queue, 0, &err);
		
		OSSemPend(get_rtc_lock(), 0, &err);
		memcpy(&now, &system_time, sizeof(INT32U));
		OSSemPost(get_rtc_lock());

		OSSemPend(get_eeprom_lock(), 0, &err);

		/* Determine event priority */
		query.type = READ_QUERY;
		query.address = EE_PRIORITES_JOURNAL + data_ptr->code;
		query.size = 1;
		query.value = (unsigned char *)(&prio);
		OSMboxPost(get_eeprom_query_mbox(), &query);

		/* Wait for data */
		rep = (eeprom_query*)OSMboxPend(get_eeprom_response_mbox(), 0, &err);

		switch (prio)
		{
			case PRIO_HIGH:
				addr_base = EE_LOG;
				break;

			case PRIO_MEDIUM:
				addr_base = EE_LOG + 256;
				break;

			case PRIO_LOW:
				addr_base = EE_LOG + 512;
				break;

			default:
				addr_base = EE_LOG;
		}

		addr_base += courant*entry_size;

		/* Write the event code */
		query.type = WRITE_QUERY;
		query.address = addr_base;
		query.value = (INT8U*)&(data_ptr->code);
		query.size = sizeof(unsigned char);
		OSMboxPost(get_eeprom_query_mbox(), &query);
		addr_base += sizeof(unsigned char);

		/* Write the date */
		query.type = WRITE_QUERY;
		query.address = addr_base;
		query.value = (INT8U*)&now;
		query.size = sizeof(time_t);
		OSMboxPost(get_eeprom_query_mbox(), &query);
		addr_base += sizeof(time_t);

		/* Write the value */
		query.type = WRITE_QUERY;
		query.address = addr_base;
		query.value = (INT8U*)&(data_ptr->valeur);
		query.size = sizeof(unsigned int);
		OSMboxPost(get_eeprom_query_mbox(), &query);

		courant = (courant + 1) % 10;

		OSSemPost(get_eeprom_lock());
	}
}
